package com.example.demo.mvvm.ui.vm.activity;

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.demo.mvvm.R;
import com.example.demo.mvvm.adapter.MainViewPagerAdapter;
import com.example.demo.mvvm.databinding.ActivityMainBinding;
import com.example.demo.mvvm.ui.base.BaseViewVM;
import com.example.demo.mvvm.ui.fragment.HomeFragment;
import com.example.demo.mvvm.ui.fragment.KnowFragment;
import com.example.demo.mvvm.ui.fragment.MeFragment;
import com.example.demo.mvvm.utils.ActivityUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 80711 on 2018/5/30.
 */

public class MainVM extends BaseViewVM{
    private int[] imags = {R.drawable.main_tab_item_home_img, R.drawable.main_tab_item_know_img, R.drawable.main_tab_item_me_img};
    private String[] titles = {"首页", "知识点", "我的"};
    private ActivityMainBinding binding;
    private MainViewPagerAdapter adapter;
    private List<Fragment> fragments;

    public MainVM(final ActivityMainBinding binding , FragmentManager fragmentManager){
        this.binding = binding;

        fragments = new ArrayList<>();
        fragments.add(HomeFragment.newInstance());
        fragments.add(KnowFragment.newInstance());
        fragments.add(MeFragment.newInstance());
        adapter = new MainViewPagerAdapter(fragmentManager, titles, fragments);
        binding.container.setAdapter(adapter);
        binding.container.setOffscreenPageLimit(titles.length);
        binding.tabLayout.setupWithViewPager(binding.container);
        for (int i = 0; i < titles.length; i++) {
            final TabLayout.Tab tab = binding.tabLayout.getTabAt(i);
            final View view =  LayoutInflater.from(ActivityUtils.peek()).inflate(R.layout.main_tab_item, null);
            ImageView img = (ImageView) view.findViewById(R.id.img);
            TextView title = (TextView) view.findViewById(R.id.title);
            view.setTag(i);
            img.setImageResource(imags[i]);
            title.setText(titles[i]);
            tab.setCustomView(view);

        }

        binding.container.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                binding.toolBar.setTitle(titles[position]);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        binding.container.setCurrentItem(0, false);
        binding.toolBar.setTitle(titles[0]);
    }



}
